package br.com.sovi.gwt.client.inicio;

import br.com.sovi.gwt.client.ImagesImpl;
import br.com.sovi.gwt.client.MenuLateralPanel;
import br.com.sovi.gwt.client.application.Application;
import br.com.sovi.gwt.client.application.ApplicationConstants;
import br.com.sovi.gwt.client.application.AttributeListener;
import br.com.sovi.gwt.client.autenticacao.service.AutenticacaoService;
import br.com.sovi.gwt.client.autenticacao.service.AutenticacaoServiceAsync;
import br.com.sovi.gwt.client.component.TokenChangeController;
import br.com.sovi.gwt.client.component.centerpanel.CenterPanel;
import br.com.sovi.gwt.client.component.mainmenu.MainMenu;
import br.com.sovi.gwt.client.component.mainmenu.MainMenuOptionsEnum;
import br.com.sovi.gwt.client.component.mainmenu.MainMenuValueChangeHandler;
import br.com.sovi.gwt.client.entity.autenticacao.Usuario;
import br.com.sovi.gwt.client.images.Images;
import br.com.sovi.gwt.client.inicio.logoff.LogoffController;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.gwtext.client.core.RegionPosition;
import com.gwtext.client.util.CSS;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Viewport;
import com.gwtext.client.widgets.layout.BorderLayout;
import com.gwtext.client.widgets.layout.BorderLayoutData;
import com.gwtext.client.widgets.layout.FitLayout;

public class Main {
	private Panel borderPanel;

	private HTML html;

	private TokenChangeController tokenChangeController;

	public Main() {
		CSS.swapStyleSheet("theme", "extjs/resources/css/xtheme-darkgray.css");

		AutenticacaoServiceAsync autenticacaoServiceAsync = GWT.create(AutenticacaoService.class);
		autenticacaoServiceAsync.getUsuarioLogado(new AsyncCallback<Usuario>() {
			@Override
			public void onSuccess(Usuario result) {
				if (result != null) {
					Application.get().addAttribute(ApplicationConstants.USUARIO_LOGADO_ATTR, result);
				}
				else {
					Application.get().removeAttribute(ApplicationConstants.USUARIO_LOGADO_ATTR);
				}
			}

			@Override
			public void onFailure(Throwable caught) {
				Application.get().removeAttribute(ApplicationConstants.USUARIO_LOGADO_ATTR);
			}
		});

		Application.get().addAttributeListener(new AttributeListener() {
			@Override
			public void attributeAdded(String key, Object value) {
				if (key.equals(ApplicationConstants.USUARIO_LOGADO_ATTR) && (value instanceof Usuario)) {
					startSystemPanel();
				}
			}

			@Override
			public void attributeRemoved(String key) {
				if (key.equals(ApplicationConstants.USUARIO_LOGADO_ATTR)) {
					startLoginPanel();
				}
			}
		});

		History.addValueChangeHandler(new ValueChangeHandler<String>() {
			@Override
			public void onValueChange(ValueChangeEvent<String> event) {
				if (ApplicationConstants.LOGOFF_TOKEN.equals(event.getValue())) {
					startLoginPanel();
					new LogoffController().efetuarLogoff();
				}
			}
		});

		History.newItem(MainMenuOptionsEnum.INICIO.getToken());
	}

	private void startLoginPanel() {
		new Viewport(new InicioLoginPanel());
	}

	private void startSystemPanel() {
		Panel panel = new Panel();
		panel.setBorder(false);
		panel.setPaddings(2);
		panel.setLayout(new FitLayout());

		panel.add(mainBorderPanel());

		// para mostrar a página do token atual.
		tokenChangeController.onTokenChange();

		buildTopHtml();

		new Viewport(panel);
	}

	private Panel mainBorderPanel() {
		borderPanel = new Panel();
		borderPanel.setLayout(new BorderLayout());

		html = new HTML();
		buildTopHtml();

		borderPanel.add(html, new BorderLayoutData(RegionPosition.NORTH));
		borderPanel.add(createBottomPanel(), new BorderLayoutData(RegionPosition.CENTER));

		return borderPanel;
	}

	public void buildTopHtml() {
		Images images = ImagesImpl.get();

		StringBuilder sb = new StringBuilder(
				"<div class=\"topPanel\"><table width='100%'><tr><td width='100px'><div class=\"topPanel_image_div\">");
		if (images != null) {
			sb.append(images.sovi_topo().getHTML());
		}
		sb.append("</div></td><td width='100%' align='right'>");
		Usuario usuario = (Usuario) Application.get().getAttribute(ApplicationConstants.USUARIO_LOGADO_ATTR);

		if (usuario != null) {
			sb.append("<table><tr><td class='topPanel_usuarioNome'>").append(usuario.getNome());
			sb.append("</td><td class='topPanel_sair'>");
			sb.append("<a href='#").append(ApplicationConstants.LOGOFF_TOKEN).append(
					"' class='topPanel_sairButton'>Sair</a>");
			sb.append("</td></tr></table>");
		}

		sb.append("</td></tr></table></div>");

		html.setHTML(sb.toString());
	}

	private Panel createBottomPanel() {
		final Panel borderPanel = new Panel();
		borderPanel.setLayout(new BorderLayout());

		MenuLateralPanel menuLateralPanel = new MenuLateralPanel();
		menuLateralPanel.collapse();

		CenterPanel centerPanel = new CenterPanel();
		centerPanel.setLayout(new FitLayout());

		tokenChangeController = new TokenChangeController(menuLateralPanel, centerPanel);

		History.addValueChangeHandler(new MainMenuValueChangeHandler(tokenChangeController));

		borderPanel.add(new MainMenu(), new BorderLayoutData(RegionPosition.NORTH));
		borderPanel.add(menuLateralPanel, new BorderLayoutData(RegionPosition.WEST));
		borderPanel.add(centerPanel, new BorderLayoutData(RegionPosition.CENTER));

		return borderPanel;
	}

}
